package com.alliky.cart.ui.fragment

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadState
import androidx.paging.LoadStates
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alliky.cart.R
import com.alliky.cart.databinding.FragmentCartBinding
import com.alliky.cart.ui.adapter.RecommendAdapter
import com.alliky.cart.ui.viewmodel.CartViewModel
import com.alliky.common.router.RoutePath
import com.alliky.core.base.BaseFragment
import kotlinx.coroutines.flow.collectLatest

@ExperimentalPagingApi
@Route(path = RoutePath.Cart.CartFragment)
class CartFragment : BaseFragment<FragmentCartBinding>() {

    private val mViewModel: CartViewModel by activityViewModels()
    private var mRecommendAdapter: RecommendAdapter = RecommendAdapter()

    override fun getLayoutId(): Int {
        return R.layout.fragment_cart
    }

    override fun initData(savedInstanceState: Bundle?) {
        mBinding.recyclerViewRecommend.apply {
            layoutManager = GridLayoutManager(requireContext(), 2)
            adapter = mRecommendAdapter
        }
        mBinding.refreshLayout.setOnRefreshListener {
            mRecommendAdapter.refresh()
        }

        lifecycleScope.launchWhenCreated {
            mRecommendAdapter.loadStateFlow.collectLatest {
//                mBinding.refreshLayout.isRefreshing = it.refresh is LoadState.Loading
                if (it.refresh !is LoadState.Loading) {
                    mBinding.refreshLayout.finishRefresh()
                }
            }
        }

        lifecycleScope.launchWhenCreated {
            mViewModel.recommondPagingFlow().collectLatest { data ->
                mRecommendAdapter!!.submitData(data)
            }
        }
    }

    override fun initObservable() {

    }
}